package com.chenjun.mysite.module.sys.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.chenjun.mysite.module.sys.entity.Menu;
import com.chenjun.mysite.module.sys.entity.MenuCategory;
import com.chenjun.mysite.module.sys.entity.User;
import com.chenjun.mysite.module.sys.service.MenuCategoryService;
import com.chenjun.mysite.module.sys.service.MenuService;
import com.chenjun.mysite.module.sys.service.UserService;


//@WebServlet("/LoginController")
// 暂时不启用Servlet 3.0

public class LoginController extends HttpServlet
{
	private static final String login_authentication = "loginAuthentication"; 
	private UserService userService = new UserService();
	private MenuCategoryService menuCategoryService = new MenuCategoryService();
	private MenuService menuService = new MenuService();
	
	public enum IsLogin
	{
		Y,N
	}
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 495071627848794336L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		this.doPost(request, response);
	}
		

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String action = request.getParameter("action");
		if(login_authentication.equals(action))
		{
			this.userAuthen(request,response);
		}
	}
	
	private void userAuthen(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if(StringUtils.isBlank(username) || StringUtils.isBlank(password))
		{
			return;
		}
		User user = userService.findByName(username);
		if(password.equals(user.getPassword()))
		{
			HttpSession httpSession = request.getSession();
			httpSession.setAttribute("isLogin", IsLogin.Y.toString());
			List<MenuCategory> menuCategories = new ArrayList<MenuCategory>();
			menuCategories = menuCategoryService.selectAll(null);
			for(MenuCategory mc : menuCategories)
			{
				Long menuCategoryId = mc.getId();
				List<Menu> menus = menuService.findByMenuCategoryId(menuCategoryId);
				mc.setMenus(menus);
			}
			httpSession.setAttribute("menuCategoryList", menuCategories);
			response.getWriter().write("loginSuccess");
		}
	}
}
